﻿using UnityEngine;
using UnityEngine.UI;

namespace Toolkit.UI.Follow
{
    public class UIFollower : MonoBehaviour
    {
        private Transform _target;
        private Camera _mainCamera;
        private Canvas _canvas;

        private void Awake()
        {
            _mainCamera = Camera.main;
            _canvas = GetComponent<Graphic>().canvas;
        }

        private void LateUpdate()
        {
            if (_target == null)
                return;
            Vector3 screenPoint = _mainCamera.WorldToScreenPoint(_target.position);
            RectTransformUtility.ScreenPointToWorldPointInRectangle(_canvas.transform as RectTransform, screenPoint, _canvas.worldCamera, out Vector3 worldPosition);
            transform.position = worldPosition;
        }

        public void SetTarget(Transform value)
        {
            _target = value;
            LateUpdate();
        }
    }
}